package cn.rocksolid.sport.common.task;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExecutorServiceUtils {

  private static final Logger LOGGER = LoggerFactory.getLogger(ExecutorServiceUtils.class);

  private static final int MAX_TP_SIZE = 128;
  private static final int MAX_TP_SHUTDOWN_WAIT = 60;

  private ExecutorServiceUtils() {
  }

  public static ExecutorService init() {
    return init(MAX_TP_SIZE);
  }

  public static ExecutorService init(int size) {
    return Executors.newFixedThreadPool(size);
  }

  public static synchronized void destroy(ExecutorService executorService) {
    if (null == executorService) {
      return;
    }
    executorService.shutdown();
    try {
      if (!executorService.awaitTermination(MAX_TP_SHUTDOWN_WAIT, TimeUnit.SECONDS)) {
        executorService.shutdownNow();
        if (!executorService.awaitTermination(MAX_TP_SHUTDOWN_WAIT, TimeUnit.SECONDS)) {
          LOGGER.warn("The RockSolid transaction executor service did not terminate correctly");
        }
      }
    } catch (InterruptedException ie) {
      executorService.shutdownNow();
      Thread.currentThread().interrupt();
    }
  }

}
